{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# OpenAI x Qdrant\n",
    "\n",
    "## Binary Quantization with OpenAI Ada-003 Embeddings\n",
    "\n",
    "This notebook demonstrates how to use Qdrant to index and search OpenAI Ada-003 embeddings. We will compare the production-like search performance of Qdrant with Binary Quantization with the brute-force search. We will use [Qdrant Cloud](https://qdrant.to/cloud?utm_source=qdrant&utm_medium=social&utm_campaign=binary-openai-v3&utm_content=article) to index and search the embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "\n",
    "import loguru\n",
    "import numpy as np\n",
    "import random\n",
    "from datasets import load_dataset\n",
    "from datasets.exceptions import DatasetNotFoundError\n",
    "from dotenv import load_dotenv\n",
    "from qdrant_client import QdrantClient, models\n",
    "from qdrant_client.models import PointStruct\n",
    "from tqdm import tqdm\n",
    "\n",
    "load_dotenv()  # take environment variables from .env\n",
    "logger = loguru.logger\n",
    "logger.add(\"logs.log\", format=\"{time} {level} {message}\", level=\"INFO\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup a Qdrant Client connection\n",
    "\n",
    "We will use the `qdrant-client` python package to interact with Qdrant. You can install it with `pip install qdrant-client`. We manage our dependencies using Poetry, so you can install all the dependencies with `poetry install`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = QdrantClient(\n",
    "    url=os.getenv(\"QDRANT_URL\"),\n",
    "    api_key=os.getenv(\"QDRANT_API_KEY\"),\n",
    "    timeout=100,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bs = 512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_combinations = [\n",
    "    # {\n",
    "    #     \"model_name\": \"text-embedding-3-large\",\n",
    "    #     \"dimensions\": 3072,\n",
    "    # },\n",
    "    # {\n",
    "    #     \"model_name\": \"text-embedding-3-large\",\n",
    "    #     \"dimensions\": 1024,\n",
    "    # },\n",
    "    # {\n",
    "    #     \"model_name\": \"text-embedding-3-large\",\n",
    "    #     \"dimensions\": 1536,\n",
    "    # },\n",
    "    {\n",
    "        \"model_name\": \"text-embedding-3-small\",\n",
    "        \"dimensions\": 512,\n",
    "    },\n",
    "    # {\n",
    "    #     \"model_name\": \"text-embedding-3-small\",\n",
    "    #     \"dimensions\": 1024,\n",
    "    # },\n",
    "    # {\n",
    "    #     \"model_name\": \"text-embedding-3-small\",\n",
    "    #     \"dimensions\": 1536,\n",
    "    # },\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[32m2024-02-06 12:17:09.274\u001b[0m | \u001b[1mINFO    \u001b[0m | \u001b[36m__main__\u001b[0m:\u001b[36m<module>\u001b[0m:\u001b[36m26\u001b[0m - \u001b[1mCreated collection dbpedia-text-embedding-3-small-512\u001b[0m\n",
      "\u001b[32m2024-02-06 12:17:15.988\u001b[0m | \u001b[1mINFO    \u001b[0m | \u001b[36m__main__\u001b[0m:\u001b[36m<module>\u001b[0m:\u001b[36m36\u001b[0m - \u001b[1mLoaded Qdrant/dbpedia-entities-openai3-text-embedding-3-small-512-100K dataset\u001b[0m\n",
      "\u001b[32m2024-02-06 12:17:35.932\u001b[0m | \u001b[1mINFO    \u001b[0m | \u001b[36m__main__\u001b[0m:\u001b[36m<module>\u001b[0m:\u001b[36m46\u001b[0m - \u001b[1mLoaded 100000 points\u001b[0m\n",
      "\u001b[32m2024-02-06 12:17:36.688\u001b[0m | \u001b[1mINFO    \u001b[0m | \u001b[36m__main__\u001b[0m:\u001b[36m<module>\u001b[0m:\u001b[36m50\u001b[0m - \u001b[1mCollection is empty. Begin upsert.\u001b[0m\n",
      "100%|██████████| 196/196 [03:19<00:00,  1.02s/it]\n",
      "\u001b[32m2024-02-06 12:20:56.677\u001b[0m | \u001b[1mINFO    \u001b[0m | \u001b[36m__main__\u001b[0m:\u001b[36m<module>\u001b[0m:\u001b[36m61\u001b[0m - \u001b[1mCollection dbpedia-text-embedding-3-small-512 is ready\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "for combination in dataset_combinations:\n",
    "    MODEL_NAME, DIMENSIONS = combination[\"model_name\"], combination[\"dimensions\"]\n",
    "    DATASET_NAME = f\"Qdrant/dbpedia-entities-openai3-{MODEL_NAME}-{DIMENSIONS}-100K\"\n",
    "    collection_name = f\"dbpedia-{MODEL_NAME}-{DIMENSIONS}\"\n",
    "    embedding_column_name = f\"{MODEL_NAME}-{DIMENSIONS}-embedding\"\n",
    "    try:\n",
    "        client.recreate_collection(\n",
    "            collection_name=collection_name,\n",
    "            vectors_config=models.VectorParams(\n",
    "                size=DIMENSIONS,\n",
    "                distance=models.Distance.COSINE,\n",
    "            ),\n",
    "            optimizers_config=models.OptimizersConfigDiff(\n",
    "                indexing_threshold=0,\n",
    "                # Turn off indexing for faster upserts\n",
    "            ),\n",
    "            quantization_config=models.BinaryQuantization(\n",
    "                binary=models.BinaryQuantizationConfig(always_ram=True),\n",
    "            ),\n",
    "            shard_number=2,\n",
    "        )\n",
    "    except Exception as e:\n",
    "        collection_info = client.get_collection(collection_name=collection_name)\n",
    "        logger.error(f\"Collection {collection_name} already exists with {collection_info.points_count} points. {e}\")\n",
    "        continue\n",
    "    logger.info(f\"Created collection {collection_name}\")\n",
    "    try:\n",
    "        dataset = load_dataset(\n",
    "        DATASET_NAME,\n",
    "        streaming=False,\n",
    "        split=\"train\",\n",
    "    )\n",
    "    except DatasetNotFoundError:\n",
    "        logger.error(f\"Dataset {DATASET_NAME} not found\")\n",
    "        continue\n",
    "    logger.info(f\"Loaded {DATASET_NAME} dataset\")\n",
    "    points = [\n",
    "        {\n",
    "            \"id\": i,\n",
    "            \"vector\": embedding,\n",
    "            \"payload\": {\"text\": data[\"text\"], \"title\": data[\"title\"]},\n",
    "        }\n",
    "        for i, (embedding, data) in enumerate(zip(dataset[embedding_column_name], dataset))\n",
    "    ]\n",
    "    points = [PointStruct(**point) for point in points]\n",
    "    logger.info(f\"Loaded {len(points)} points\")\n",
    "    \n",
    "    collection_info = client.get_collection(collection_name=collection_name)\n",
    "    if collection_info.vectors_count == 0:\n",
    "        logger.info(\"Collection is empty. Begin upsert.\")\n",
    "        for i in tqdm(range(0, len(points), bs)):\n",
    "            slice_points = points[i : i + bs]  # Create a slice of bs points\n",
    "            client.upsert(\n",
    "                collection_name=collection_name, points=slice_points, wait=True\n",
    "            )\n",
    "    # After the upsert, we can turn on indexing for faster search\n",
    "    client.update_collection(\n",
    "        collection_name=f\"{collection_name}\",\n",
    "        optimizer_config=models.OptimizersConfigDiff(indexing_threshold=20000),\n",
    "    )\n",
    "    logger.info(f\"Collection {collection_name} is ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 💡 Note on Indexing: Since Indexing is a background process, it does not affect our exact search performance. Turning off the indexing allows for faster uploads and writes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a valuation split for the BQ to Compare exact with approximate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "oversampling_range = np.arange(1.0, 3.1, 1.0)\n",
    "rescore_range = [True, False]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parameterized Search\n",
    "\n",
    "We will use the `qdrant-client` to perform a parameterized search. We will compare the exact search performance with the approximate search performance. We will use the `search` method to perform the exact search with exact=True."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def parameterized_search(\n",
    "    point,\n",
    "    oversampling: float,\n",
    "    rescore: bool,\n",
    "    exact: bool,\n",
    "    collection_name: str,\n",
    "    ignore: bool = False,\n",
    "    limit: int = 10,\n",
    "):\n",
    "    if exact:\n",
    "        return client.search(\n",
    "            collection_name=collection_name,\n",
    "            query_vector=point.vector,\n",
    "            search_params=models.SearchParams(exact=exact),\n",
    "            limit=limit,\n",
    "        )\n",
    "    else:\n",
    "        return client.search(\n",
    "            collection_name=collection_name,\n",
    "            query_vector=point.vector,\n",
    "            search_params=models.SearchParams(\n",
    "                quantization=models.QuantizationSearchParams(\n",
    "                    ignore=ignore,\n",
    "                    rescore=rescore,\n",
    "                    oversampling=oversampling,\n",
    "                ),\n",
    "                exact=exact,\n",
    "            ),\n",
    "            limit=limit,\n",
    "        )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for combination in dataset_combinations:\n",
    "    MODEL_NAME, DIMENSIONS = combination[\"model_name\"], combination[\"dimensions\"]\n",
    "    DATASET_NAME = f\"Qdrant/dbpedia-entities-openai3-{MODEL_NAME}-{DIMENSIONS}-100K\"\n",
    "    collection_name = f\"dbpedia-{MODEL_NAME}-{DIMENSIONS}\"\n",
    "    embedding_column_name = f\"{MODEL_NAME}-{DIMENSIONS}-embedding\"\n",
    "    dataset = load_dataset(\n",
    "        DATASET_NAME,\n",
    "        streaming=False,\n",
    "        split=\"train\",\n",
    "    )\n",
    "    ds = dataset.train_test_split(test_size=0.001, shuffle=True, seed=37)[\"test\"]\n",
    "    ds = ds.to_pandas().to_dict(orient=\"records\")\n",
    "    logger.info(f\"Loaded {DATASET_NAME} dataset\")\n",
    "    results = []\n",
    "    with open(f\"results-{MODEL_NAME}-{DIMENSIONS}.json\", \"w+\") as f:\n",
    "        for element in tqdm(ds):\n",
    "            # print(element.payload[\"text\"])\n",
    "            # print(\"Oversampling\")\n",
    "            point = PointStruct(\n",
    "                id=random.randint(0, 100000),\n",
    "                vector=element[embedding_column_name],\n",
    "            )\n",
    "            ## Running Grid Search\n",
    "            for oversampling in oversampling_range:\n",
    "                for rescore in rescore_range:\n",
    "                    limit_range = [100, 50, 20, 10, 5]\n",
    "                    for limit in limit_range:\n",
    "                        try:\n",
    "                            exact = parameterized_search(\n",
    "                                point=point,\n",
    "                                oversampling=oversampling,\n",
    "                                rescore=rescore,\n",
    "                                exact=True,\n",
    "                                collection_name=collection_name,\n",
    "                                limit=limit,\n",
    "                            )\n",
    "                            hnsw = parameterized_search(\n",
    "                                point=point,\n",
    "                                oversampling=oversampling,\n",
    "                                rescore=rescore,\n",
    "                                exact=False,\n",
    "                                collection_name=collection_name,\n",
    "                                limit=limit,\n",
    "                            )\n",
    "                        except Exception as e:\n",
    "                            print(f\"Skipping point: {point}\\n{e}\")\n",
    "                            continue\n",
    "\n",
    "                        exact_ids = [item.id for item in exact]\n",
    "                        hnsw_ids = [item.id for item in hnsw]\n",
    "                        # logger.info(f\"Exact: {exact_ids}\")\n",
    "                        # logger.info(f\"HNSW: {hnsw_ids}\")\n",
    "\n",
    "                        accuracy = len(set(exact_ids) & set(hnsw_ids)) / len(exact_ids)\n",
    "\n",
    "                        if accuracy is None:\n",
    "                            continue\n",
    "\n",
    "                        result = {\n",
    "                            \"query_id\": point.id,\n",
    "                            \"oversampling\": oversampling,\n",
    "                            \"rescore\": rescore,\n",
    "                            \"limit\": limit,\n",
    "                            \"accuracy\": accuracy,\n",
    "                        }\n",
    "                        f.write(json.dumps(result))\n",
    "                        f.write(\"\\n\")\n",
    "                        logger.info(result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "fastembed",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
